<template>
	<div class="">
		<div class="flex justify-between items-center">
			<sports-toggle-group v-model="sportId" />
			<base-popselect
				v-model="regionId"
				:options="regionOptions"
				imgType="server"
				imgDefault="sports/nation-default"
				hasAll />
		</div>
		<base-list-plus
			:auto="false"
			:loading="loading"
			:isFinish="isFinish"
			:isEmpty="isEmpty"
			:error="error"
			@load="page++">
			<div ref="el" class="mt-[10px] grid gap-[10px]" :class="colsClass">
				<sports-league-item
					v-for="item in showLeagueList"
					:key="item.leagueId"
					:data="item"></sports-league-item>
			</div>
		</base-list-plus>
	</div>
</template>

<script lang="ts" setup>
import SportsLeagueItem from '../sports-league-item/index.vue'
import { BaseListPlus, BasePopselect } from '@/components/base'
import { SportsToggleGroup } from '@/components/sports'
import { ref, watch, computed } from 'vue'
import { SportsType } from '@/enums'
import { LeagueType, RegionType } from '@/types'
import { useListCols, useRequest } from '@/hooks'
import { getSportsRegions } from '@/api/betting'
import { useAppStore } from '@/store'

const appStore = useAppStore()

const sportId = ref(SportsType.football)

const regionId = ref('')

const regionList = ref<RegionType[]>([])

const regionOptions = computed(() =>
	regionList.value.map((item: RegionType) => ({
		id: item.regionId,
		text: item.regionName,
		img: item.icon
	}))
)

const el = ref(null)

const { colsClass } = useListCols(el)

const page = ref(1)

const pageSize = 12

const leagueList = computed(() => {
	const res: LeagueType[] = []
	regionList.value.forEach((region: RegionType) => {
		if (!regionId.value || regionId.value === region.regionId) {
			region.leagues.forEach((league: any) => {
				res.push({
					...league,
					sportId: sportId.value,
					regionId: region.regionId,
					regionName: region.regionName,
					regionIcon: region.icon
				})
			})
		}
	})
	return res
})

const showLeagueList = computed(() => leagueList.value.slice(0, page.value * pageSize))

const isFinish = computed(() => leagueList.value.length <= page.value * pageSize)

const { run, loading, error, isEmpty } = useRequest<LeagueType>(getSportsRegions, {
	onSuccess: (data: any) => {
		regionList.value = data.list
	}
})

const params = computed(() => ({
	location: appStore.region,
	locale: appStore.lang,
	sportId: sportId.value
}))

const search = () => {
	page.value = 1
	regionList.value = []
	run(params.value)
}

watch(
	params,
	() => {
		search()
	},
	{ immediate: true }
)
</script>
